let isScrolling = false;
let scrollSpeed = 5;
let scrollInterval;
let isLoading = false;

// 读取保存的速度
chrome.storage.local.get(['scrollSpeed'], (result) => {
    if (result.scrollSpeed) {
        document.getElementById('speedInput').value = result.scrollSpeed;
        document.querySelector('.speed-value').textContent = result.scrollSpeed;
    }
});

// 处理速度输入
document.getElementById('speedInput').addEventListener('input', function(e) {
    const speed = parseInt(e.target.value) || 5;
    document.querySelector('.speed-value').textContent = speed;
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            action: 'setSpeed',
            speed: speed
        });
    });
    chrome.storage.local.set({ scrollSpeed: speed });
});

// 创建控制按钮
function createScrollButton() {
    const button = document.createElement('button');
    button.id = 'auto-scroll-btn';
    button.textContent = '开始滚动';
    button.className = 'auto-scroll-button';
    document.body.appendChild(button);

    button.addEventListener('click', () => {
        isScrolling = !isScrolling;
        button.textContent = isScrolling ? '停止滚动' : '开始滚动';

        if (isScrolling) {
            startScrolling();
        } else {
            stopScrolling();
        }
    });
}

// 检查是否需要加载更多
async function checkAndLoadMore() {
    // 如果正在加载中，直接返回
    if (isLoading) return false;

    // 检查是否滚动到底部
    const isBottom = (window.innerHeight + window.scrollY) >= document.body.offsetHeight - 100;
    if (!isBottom) return false;

    // 检查页面是否有加载更多的按钮或元素
    const loadMoreButton = document.querySelector('.load-more, .loadMore, [class*="load-more"], [class*="loadMore"]');
    if (loadMoreButton) {
        try {
            isLoading = true;
            loadMoreButton.click();
            // 等待内容加载
            await new Promise(resolve => setTimeout(resolve, 1000));
            isLoading = false;
            return true;
        } catch (error) {
            console.error('加载更多失败：', error);
            isLoading = false;
            return false;
        }
    }

    return false;
}

// 开始滚动
async function startScrolling() {
    scrollInterval = setInterval(async() => {
        window.scrollBy(0, scrollSpeed);

        // 检查是否需要加载更多
        const loadedMore = await checkAndLoadMore();

        // 如果已经到底部且没有加载到更多内容，则停止滚动
        if (!loadedMore && (window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
            stopScrolling();
            isScrolling = false;
            document.getElementById('auto-scroll-btn').textContent = '开始滚动';
        }
    }, 16);
}

// 停止滚动
function stopScrolling() {
    clearInterval(scrollInterval);
}

// 监听来自 popup 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'setSpeed') {
        scrollSpeed = request.speed;
        if (isScrolling) {
            stopScrolling();
            startScrolling();
        }
    }
});

// 初始化
createScrollButton();

// 处理隐藏按钮的切换
document.getElementById('hideToggle').addEventListener('change', function(e) {
    const isHidden = e.target.checked;
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            action: 'toggleHide',
            isHidden: isHidden
        });
    });
});

// 读取保存的隐藏状态
chrome.storage.local.get(['isHidden'], (result) => {
    if (result.isHidden) {
        document.getElementById('hideToggle').checked = result.isHidden;
    }
});

// 读取保存的滚动状态
chrome.storage.local.get(['isScrolling'], (result) => {
    if (result.isScrolling) {
        document.getElementById('scrollToggle').checked = result.isScrolling;
    }
});

// 处理滚动开关
document.getElementById('scrollToggle').addEventListener('change', function(e) {
    const isScrolling = e.target.checked;
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
            action: 'toggleScroll',
            isScrolling: isScrolling
        });
    });
    chrome.storage.local.set({ isScrolling: isScrolling });
});